<template>
  <div class="trial-file-content">
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      ref="crud"
      :before-open="beforeOpen"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu="{ row }">
        <el-button text type="primary" @click="handleMenu(0, row)">下 载</el-button>
      </template>
      <!-- 自定义搜索栏 -->
      <template #search="{}">
        <div style="height: 40px">
          <avue-form
            :option="fileOption"
            v-model="fileForm"
            :upload-before="uploadBefore"
            :upload-after="uploadAfter"
          ></avue-form>
        </div>
      </template>
    </avue-crud>
  </div>
</template>
<script setup>
import { informationList,informationListWithTrial, informationRemove, informationSubmit } from '@/api/trial/trial';
import { getDictionary } from '@/api/system/dictbiz';
import { ref, reactive, computed, onMounted, defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import { submit } from '@/api/base/region';
import { findObject } from "@smallwei/avue";
const route = useRoute();
const emit = defineEmits();
const routerQuery = ref({});
routerQuery.value = route.query;
const router = useRouter();
const crud = ref(null);
const store = useStore();
const option = ref({
  height: 'auto',
  calcHeight: 30,
  tip: false,
  searchShow: true,
  searchMenuSpan: 24,
  searchMenuPosition: 'right',
  border: true,
  index: true,
  viewBtn: true,
  selection: true,
  dialogClickModal: false,
  align: 'center',
  indexWidth: 80,
  indexLabel: '编号',
  // menu: false,
  // addBtn: false,
  labelWidth: 145,
  viewBtn: false,
  editBtn: false,
  addBtn: false,
  // menuWidth: 300,
  searchBtn: false,
  emptyBtn: false,
  column: [
    {
      label: '文件类型',
      prop: 'type',
      type: 'select',
      // dicUrl: '/api/blade-system/dict-biz/dictionary?code=information_type',
      dicData: [],
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      filterable: true,
      overHidden: true,
    },
    {
      label: '文件名称',
      prop: 'name',
      type: 'input',
      filterable: true,
      overHidden: true,
    },
    {
      label: '上传时间',
      prop: 'createTime',
      type: 'input',
      filterable: true,
      overHidden: true,
    },
  ],
});
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const data = ref([]);

let fileForm = ref({});
const fileOption = ref({
  submitBtn: false,
  emptyBtn: false,
  column: [
    {
      label: '资料类型',
      prop: 'type',
      type: 'select',
      // dicUrl: '/api/blade-system/dict-biz/dictionary?code=information_type',
      dicData: [],
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      filterable: true,
      overHidden: true,
    },
    {
      label: '上传文件',
      prop: 'link',
      type: 'upload',
      // slot: true,
      dataType: 'string',
      limit: 1,
      fileType: 'doc,docx,xls,xlsx,pdf,txt',
      action: '/blade-resource/oss/endpoint/put-file',
      propsHttp: {
        res: 'data',
        url: 'link',
      },
      // tip: '只能上传doc/docx/excel文件',
    },
  ],
});

let getTrialStatus = ref(localStorage.getItem('storageTrialStatus'));

onMounted(() => {
  initData();
});
const initData = () => {
  option.value.delBtn = getTrialStatus.value == '1' ? true : false;
  // routerQuery.value.caseManagementId是“我的病例”里面的相关资料
  // routerQuery.value.trialId是“业务管理”里面的相关资料
  let params = routerQuery.value.trialId ? 'information_type' : 'case_data_type';
  getDictionary({code:params}).then((res) => {
    var column = findObject(option.value.column, "type");
    var column1 = findObject(fileOption.value.column, "type");
    console.log(res);
    column.dicData = res.data.data;
    column1.dicData = res.data.data;
  })
};
// 操作栏点击事件
const handleMenu = (type, row) => {
  switch (type) {
    case 0:
      window.open(row.link);
      break;
  }
};
// 上传文件前的回调函数
const uploadBefore = (file, done) => {
  loading.value = true;
  if (fileForm.value.type === '') {
    ElMessage({
      message: '请选择文件类型！',
      type: 'warning',
    });
    // done();
    loading.value = false;
    return;
  }
  done();
};
// 上传文件后的回调函数
const uploadAfter = (res, done) => {
  fileForm.value.link = res.link;
  fileForm.value.name = res.originalName;
  // routerQuery.value.caseManagementId是“我的病例”里面的相关资料
  // routerQuery.value.trialId是“业务管理”里面的相关资料
  fileForm.value.trial = routerQuery.value.trialId || null;
  fileForm.value.caseId = routerQuery.value.caseManagementId || null;
  fileForm.value.classification = routerQuery.value.caseManagementId ? '1' : null;
  console.log(fileForm.value, res);
  informationSubmit(fileForm.value).then(res => {
    onLoad(page.value);
    ElMessage.success('操作成功!');
    done();
    fileForm.value.link = "";
    fileForm.value.type = "";
  });
};
const rowSave = (row, done, loading) => {
  add(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return informationRemove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};
const beforeOpen = (done, type) => {
  if (['add'].includes(type)) {
    const createUser = findObject(options.value.column, 'createUser');
    createUser.value = userInfo.value.user_id;
  }
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
    trial:routerQuery.value.trialId || null,
    caseId:routerQuery.value.caseManagementId || null,
    classification:routerQuery.value.caseManagementId ? '1' : null,
  };
  if(routerQuery.value.caseManagementId){
    informationList(page.currentPage, page.pageSize, values).then(res => {
      const DATA = res.data.data;
      page.total = DATA.total;
      data.value = DATA.records;
      loading.value = false;
      selectionClear();
    });
  }else {
    informationListWithTrial(page.currentPage, page.pageSize, values).then(res => {
      const DATA = res.data.data;
      page.total = DATA.total;
      data.value = DATA.records;
      loading.value = false;
      selectionClear();
    });
  }
};
</script>
<style scoped>
.trial-file-content {
  width: 90%;
  height: 100%;
}
</style>